import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入登录和注册路由
import Login from '../views/Login/index.vue'
import Layout from '../views/Layout/index.vue'

import store from '../store/index'
// 导入子路由
// import Register from '../views/Register/index.vue'
// import Home from '../views/Layout/Home/index.vue'
// import UserInfo from '../views/Layout/User/UserInfo.vue'
// import UserAvatar from '../views/Layout/User/UserAvatar.vue'
// import UserPwd from '../views/Layout/User/UserPwd.vue'
// import ActCate from '../views/Layout/Acticle/ActCate.vue'
// import ArtList from '../views/Layout/Acticle/ArtList.vue'
// import _404 from '../views/404/index.vue'
const Register = () => import('../views/Register/index.vue')
const Home = () => import('../views/Layout/Home/index.vue')
const UserInfo = () => import('../views/Layout/User/UserInfo.vue')
const UserAvatar = () => import('../views/Layout/User/UserAvatar.vue')
const UserPwd = () => import('../views/Layout/User/UserPwd.vue')
const ActCate = () => import('../views/Layout/Acticle/ActCate.vue')
const ArtList = () => import('../views/Layout/Acticle/ArtList.vue')
const _404 = () => import('../views/404/index.vue')

Vue.use(VueRouter)
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}
// 路由规则
const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    // 子路由规则数组
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ActCate },
      { path: 'art-list', component: ArtList }
    ]
  },
  // 配置404
  { path: '*', component: _404 }
]

const router = new VueRouter({
  routes
})
// 路由守卫白名单数组
const whiteList = ['/login', '/register']
// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否有token
  const token = store.state.user.token
  if (token) {
    next()
  } else {
    // 判断是否前往首页
    if (whiteList.includes(to.path)) { // includes 方法返回的值是布尔值
      next()
    } else {
      next('/login')
    }
  }
})

export default router
